﻿using System.Collections;
using System.Web;
using Zinnia.Lite.Core;

namespace Zinnia.Lite.Web.Core.Imp
{
    /// <summary>
    /// Http请求数据缓存
    /// </summary>
    public class PerRequestCacheManager : IHttpCacheService
    {
        private readonly HttpContextBase _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">请求内容</param>
        public PerRequestCacheManager(HttpContextBase context)
        {
            _context = context;
        }

        /// <summary>
        /// 创建缓存对象
        /// </summary>
        protected virtual IDictionary GetItems()
        {
            if (_context != null)
                return _context.Items;
            return null;
        }

        /// <summary>
        /// 获取或设置缓存数据
        /// </summary>
        /// <typeparam name="T">缓存数据类型</typeparam>
        /// <param name="key">缓存Key</param>
        /// <returns>缓存数据</returns>
        public T GetCacheOjbect<T>(string key)
        {
            var items = GetItems();
            if (items == null)
                return default(T);

            return (T)items[key];
        }

        public void Add<T>(T data, string key)
        {
            Add(data,key, -1);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存key</param>
        /// <param name="data">缓存数据</param>
        /// <param name="cacheTime">缓存时间</param>
        public void Add<T>(T data, string key, int cacheTime)
        {
            var items = GetItems();
            if (items == null)
                return;

            if (data != null)
            {
                if (items.Contains(key))
                    items[key] = data;
                else
                    items.Add(key, data);
            }
        }
        /// <summary>
        /// 移除Key对应的缓存
        /// </summary>
        /// <param name="key">要移除的Key</param>
        public void RemoveCache(params string[] key)
        {
            var items = GetItems();
            if (items == null)
                return;
            foreach (var k in key)
            {
                items.Remove(k);
            }
        }
    }
}
